<template>
  <div>
    <van-search
      v-model="keyWord"
      show-action
      label="地址"
      placeholder="请输入搜索关键词"
      background="#f88"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <div class="hisWrap">
      <h4>搜索记录</h4>
      <div class="histories">
        <div class="his" v-if="!histories.length">暂无搜索记录</div>
        <div class="his" @click="clickHis(his)" v-for="his in histories" :key="his">
          {{ his }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      keyWord: '', // 搜索关键字
      histories: localStorage.getItem('his')
        ? JSON.parse(localStorage.getItem('his'))
        : []
    }
  },
  methods: {
    clickHis (word) {
      // 点击 历史记录
      this.keyWord = word
      this.onSearch()
    },
    onSearch () {
      // 存储 搜索记录
      /*
      先取 转换成数组  操作数组 JSON.stringify存回去
      */
      let his = localStorage.getItem('his')
        ? JSON.parse(localStorage.getItem('his'))
        : []
      his.unshift(this.keyWord)
      his = [...new Set(his)]
      if (his.length >= 3) {
        his.length = 3
      }
      // 存回去
      localStorage.setItem('his', JSON.stringify(his))
      // 进入搜索结果页 并传递 搜索关键字
      this.$router.push({
        path: '/searchResult',
        query: {
          keyword: this.keyWord
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.histories{
  display: flex;
  flex-wrap: wrap;
  .his{
    padding: 5px 15px;
    background-color: #f1f1f1;
    margin-top: 10px;
    margin-left: 10px;
  }
}
</style>
